package com.guiji.quartz.domain;

import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.quartz.config.ProxyConfig;
import com.guiji.quartz.task.DataSaveUtil;
import com.guiji.quartz.util.DateFormatUtil;
import com.guiji.quartz.util.DelPicUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: gaoX
 * @date 2021/12/24 17:16
 */
public class Appleinsider {
	private static final Logger log = LoggerFactory.getLogger(Aninews.class);

	public static void mainMethod() throws Exception {
		HttpResponse response = null;
		try {
			response = HttpRequest.get("https://appleinsider.com/")
				.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
				.header("Accept-Encoding", "gzip, deflate")
				.setConnectionTimeout(15000)
				.execute();
		} catch (Exception e) {
			log.error("代理失败1" + e);
			return;
		}
		String resp = response.body();
		Set<String> resUrl = getUrl(resp);
		getContent(resUrl);

	}

	private static void getContent(Set<String> listContent) {
		for (String url : listContent) {
			log.info("getContent执行到-{},listContent长度-{}", url, listContent.size());
			String doc;
			JXDocument jxDocument;
			try {
				HttpResponse response = HttpRequest.get(url).setConnectionTimeout(15000).execute();
				doc = response.body();
				jxDocument = new JXDocument(doc);
			} catch (Exception e) {
				log.info("代理失败2" + e);
				continue;
			}
			String title = null;
			try {
				title = (String) jxDocument.sel("//h1[@class='h1-adjust']/text()").get(0);
			} catch (Exception e) {
				log.error("标题错误-------------" + url + "-------------------标题错误");
				continue;
			}
			Document document = null;
			String cont = null;
			StringBuffer content = new StringBuffer();
			try {
				document = Jsoup.parse(doc);
				cont = document.getElementsByClass("reviews").get(0).toString().replaceAll("\n","")
					.replaceAll("<html>.*?</html>","");
				ReUtil.findAll("<p>.*?</p>",cont,0).forEach(s -> {
					content.append(s.replaceAll("<.*?>","").replaceAll("&nbsp;"," ")+"$$$");
				});
			} catch (Exception e) {
				continue;
			}

			List<Object> newImgs = null;
			try {
				newImgs = jxDocument.sel("//div[@id='article-hero']//img/@src");
			} catch (Exception e) {
				log.error("获取图片失败");
			}

			Date date = new Date();

			if (content.length() > 50000 || content.toString().replaceAll("\\$|[\\s\\p{Zs}]","").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				DataSaveUtil.saveData(title, content.toString(), newImgs, url, date, "https://appleinsider.com/", "appleinsider-TechNews");
				log.info(Thread.currentThread().getName() + "-----------------appleinsider-TechNews----------------");
			} catch (Exception e) {
				continue;
			}

		}
	}

	private static Set<String> getUrl(String content) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String[] ss = sdf.format(new Date()).split("-");
		String year = ss[0].substring(2);
		String mon = ss[1];

		Set<String> res = new HashSet<>();
		String pattern = "https://appleinsider.com/articles/"+year+"/"+mon+"/[0-9]{2}/.*?\"";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(content);
		while (m.find()) {
			res.add(m.group().replaceAll("\"",""));
		}
		return res;
	}

//	public static void main(String[] args) throws Exception {
//		mainMethod();
//	}
}
